package net.borderwars.util;

import java.util.*;

/**
 * @author Eric
 *         Date: Feb 26, 2005
 *         Time: 2:00:41 PM
 */
public class Histagram {
    HashMap<Object, Integer> hm = new HashMap<Object, Integer> ();

    public void count (Object k) {
        Integer i;
        if (!hm.containsKey (k)) {
            i = 1;
        }
        else {
            i = hm.get (k);
            i++;
        }
        hm.put (k, i);
    }

    public void subtract (Object k) {
        Integer i;
        if (!hm.containsKey (k)) {
            i = -1;
        }
        else {
            i = hm.get (k);
            i--;
        }
        hm.put (k, i);
    }

    public void reset () {
        hm.clear ();
    }

    public int getCount (Object k) {
        if (!hm.containsKey (k)) {
            return (0);
        }
        else {
            return (hm.get (k));
        }
    }

    public ArrayList<Pair> getTop (int x) {
        Pair data[] = new Pair[hm.entrySet ().size ()];
        int idx = 0;
        for (Map.Entry e : hm.entrySet ()) {
            data[idx] = new Pair (e.getValue (), e.getKey ());
            idx++;
        }
        Arrays.sort (data);

        ArrayList<Pair> rtn = new ArrayList<Pair> (x);

        List<Pair> subList = rtn.subList (0, x);
        for (Pair p : subList) {
            rtn.add (p);
        }

        return (rtn);
    }

    public String toString () {
        Pair data[] = new Pair[hm.entrySet ().size ()];
        int idx = 0;
        for (Map.Entry e : hm.entrySet ()) {
            data[idx++] = new Pair (e.getValue (), e.getKey ());
        }
        Arrays.sort (data);
        StringBuffer sb = new StringBuffer (hm.entrySet ().size () * 30);
        for (Pair pair : data) {
            sb.append (pair.toString () + "\n");
        }
        return (sb.toString ());
    }

    private class Pair implements Comparable {
        public final Integer count;
        public final Object key;

        Pair (Object count, Object key) {
            this.count = (Integer) count;
            this.key = key;
        }

        public String toString () {
            return (key + "-->" + count);
        }

        public int compareTo (Object o) {
            if (o instanceof Pair) {
                Pair p = (Pair) o;
                return (p.count.compareTo (this.count));
            }
            throw new ClassCastException ("I don't appreciate being compared to others not of my kind");
        }
    }

}
